package com.dfs.parent.common.core.utils;

import com.dfs.parent.common.core.enums.ResultCode;
import com.dfs.parent.common.core.exception.DfsException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @ClassName jwtUtil
 * @Author hong
 * @Date 2019/9/26 8:31 PM
 * @Version 1.0
 **/
@Slf4j
public class JwtUtil {
    /**
     * 生成jwt token
     */
      public static String createToken(Map<String, Object> claims,String secret,Long expire) {
        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setClaims(claims)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }
    public static String createToken(Map<String, Object> claims,String secret) {
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public static Claims parseToken(String token,String secret) {
        try {
            return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        }catch (Exception e){
           log.error("校验token异常:{},异常信息:{}",token,e.getMessage());
           throw new DfsException(ResultCode.JWT_TOKEN_EXPIRE.getCode(),ResultCode.JWT_TOKEN_EXPIRE.getMsg());
        }
    }

    /**
     * token是否过期
     * @return  true：过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }


    public static void main(String[] args) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId","1223323");
        claims.put("username","45454445");
        String token = JwtUtil.createToken(claims,"f4e2e52034348f86b67cde581c0f9eb5");
        System.out.println(token);
        Claims claims1 =  JwtUtil.parseToken(token,"f4e2e52034348f86b67cde581c0f9eb5");
        System.out.println(claims1.get("userId"));


    }


}
